#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time: 2023/6/13 17:02
# @Author: Anthony (anthony66888@163.com)
# @description: 
"""
import datetime
import random
import time
import traceback
from urllib import parse
import requests
from auto_battle_room import init_login
from auto_battle_room.utils.yaml_control import YamlControl
from user_info import batch_add_balance


class AutoCreateBattle(object):
    def __init__(self):
        """
        获取玩家列表并登陆、箱子列表，可输入可固定
        """
        self.config_data = YamlControl("/data/config.yaml").read_yaml()  # 读取配置项
        self.host = self.config_data["host"]  # 获取环境域名
        self.yaml_control_user = YamlControl("/data/user_info.yaml")  # 获取机器人登陆后的token等信息
        self.yaml_control_battle = YamlControl("/data/battle_room.yaml") # 获取最新可参与的对战房间

    def get_battle_case(self):
        url = "/api/case/casePage"
        data = {
            "page": 1,
            "pageSize": 1000,
            "boxType": 1,
            "moduleId": -1,
            "visibleRoom": True,
        }
        try:
            res = requests.get(self.host + url, data)
            if res.json()["status"] == 0:
                box_list = []
                i = 0
                for box in res.json()["data"]["pageData"]:
                    if box["openPrice"] <= 25:
                        i += 1
                        box_list.append(box["id"])
                    if i == 10:
                        break
                return box_list
            else:
                return None
        except Exception as e:
            return None

    def get_random_box_list(self):
        """
        获取随机对战房的箱子组合  箱子数量阈值：【1，10】
        :return: 返回随机组合后用于对战的箱子列表
        """
        # random_box_list = []
        box_list_type = random.choice([2,2])  # 1=随机列表 2=固定列表 3=拼箱固定列表 4=随机小箱子列表
        if box_list_type == 1:
            # battle_box_list = self.get_battle_case()
            # if battle_box_list is None:
            #     battle_box_lists = []
            #
            #     for i in range(random.randint(1, 10)):
            #         # 随机选择一个元素（可重复选取）
            #         battle_box_lists.append(random.choice(
            #             self.config_data["box_list"]["random_box_list"].split(',')
            #         ))
            #     # 拼接成字符串
            #     box_config = [1, ','.join(battle_box_lists)]
            # else:
            #     box_config = [1, ','.join(battle_box_list)]
            # battle_box_list = []
            if self.get_battle_case():
                battle_box_list = self.get_battle_case()
            else:
                battle_box_list = self.config_data["box_list"]["random_box_list"].split(',')
            box_config = [1, ','.join([random.choice(battle_box_list) for i in range(random.randint(1, 10))])]

        elif box_list_type == 2:
            box_config = [2, random.choice(self.config_data["box_list"]["fixed_battle_box_list"])]
        elif box_list_type == 4:
            battle_box_list = []
            for i in range(random.randint(1, 2)):
                # 随机选择一个元素（可重复选取）
                battle_box_list.append(random.choice(
                    self.config_data["box_list"]["random_small_box"].split(',')
                ))
            # 拼接成字符串
            box_config = [4, ','.join(battle_box_list)]
        else:
            box_config = [3, random.choice(self.config_data["box_list"]["fixed_px_box_list"])]
        return box_config

    def get_request_data(self):
        """
        获取随机创建箱子的请求参数data
        :return:
        """
        box_config = self.get_random_box_list()
        if box_config[0] == 1:
            data = {
                "pos": 1,
                "mode": random.choice([0, 1]),  # 获取随机对战模式【0=欧皇、1=非酋、3=拼箱】
                "countCustomer": random.randint(2, 3),  # 获取随机房间人数 【2人或3人】
                "boxLists": box_config[1],
                "title": "521987"
            }
        elif box_config[0] == 2:
            data = {
                "pos": 1,
                "mode": random.choice([0, 1]),  # 获取随机对战模式【0=欧皇、1=非酋、3=拼箱】
                "countCustomer": random.randint(2, 3),  # 获取随机房间人数 【2人或3人】
                "boxLists": box_config[1],
                "title": "521987"
            }
        elif box_config[0] == 4:
            data = {
                "pos": 1,
                "mode": random.choice([0, 1]),  # 获取随机对战模式【0=欧皇、1=非酋、3=拼箱】
                "countCustomer": random.randint(2, 3),  # 获取随机房间人数 【2人或3人】
                "boxLists": box_config[1],
                "title": "521987"
            }
        else:
            data = {
                "pos": 1,
                "mode": 3,  # 获取随机对战模式【0=欧皇、1=非酋、3=拼箱】
                "countCustomer": 3,  # 获取随机房间人数 【2人或3人】
                "boxLists": box_config[1],
                "title": "521987"
            }
        return data

    def get_now_room_num(self):
        """
        获取当前进行中的对战房数量
        :return:
        """
        # url = "/api/battle/getCurrentPage"
        url = "/api/battle/getList"
        data = {
            "page": 1,
            "pageSize": 16,
            "mode": -1,
            "state": 0
        }
        try:
            res = requests.get(self.host + url, data)
            return res.json()["data"]["totalRows"]
        except Exception as e:
            print(f"获取当前进行中的对战房数量报错: {e}")
            traceback.print_exc()
            return None

    def able_to_join(self, room_id, token):
        """获取当前可参加的对战房间"""
        flag = False
        url = "/api/battle/getBattleDetail"
        data = {
            "battleId": room_id
        }
        headers = {
            "Token": token
        }
        try:
            res = requests.get(self.host + url, params=data, headers=headers)
            room_state = res.json()["data"]["state"]
            if room_state == 0:
                flag = True
            return flag
        except:
            pass

    def join_robot(self, battle_id, pos, token, _account):
        """
        添加机器人
        :param battle_id: 对战房间ID
        :param token: 添加机器人的用户
        :return:
        """
        url = "/api/battle/joinBot"
        headers = {
            "Token": token,
            "Content-Type": "application/x-www-form-urlencoded"
        }
        data = {
            "battleId": battle_id,
            "pos": pos
        }
        data = parse.urlencode(data)
        try:
            # requests.post(url=self.host + url, data=data, headers=headers)
            response = requests.post(url=self.host + url, data=data, headers=headers)
            if response.json()["status"] == 401:
                init_login(account=_account)

        except:
            pass

    def get_user_balance(self, token):
        """
        获取用户当前星币余额
        :return:
        """
        # url = "/api/personalCenter/customerDetail"
        url = "/api/profile/userInfo"
        headers = {
            "Token": token
        }
        res = requests.get(self.host + url, headers)
        if res.json()["status"] == 0:
            return res.json()["data"]["balance"]
        else:
            return 50

    def random_create_room(self, user_info):
        # i = 0
        url = "/api/battle/create"
        if self.get_user_balance(user_info["token"]) < 10:
            batch_add_balance(phone1=user_info['account'])
            return 400
        else:
            headers = {
                "Token": user_info["token"],
                "Content-Type": "application/x-www-form-urlencoded"
            }
            data_init = self.get_request_data()
            data = parse.urlencode(data_init)

            # requests.post(url=self.host + url, data=data, headers=headers)
            try:
                response = requests.post(url=self.host + url, data=data, headers=headers)
                time.sleep(1)
                if response.json()["status"] == 0:
                    # 随机创建房间后立即加入机器人
                    battle_code = response.json()["data"]
                    if random.randint(1, 10) == 1:
                        for j in range(2, 5):
                            if self.able_to_join(battle_code, user_info["token"]):
                                self.join_robot(battle_code, j, user_info["token"], _account=user_info['account'])
                                time.sleep(1)
                    return 0
                elif response.json()["status"] == 1:  # "賬戶餘額不足,請先充值"
                    print(f"账户余额不足，账户为{user_info['account']},报错为{response.json()['msg']}")
                    batch_add_balance(phone1=user_info['account'])
                    time.sleep(1)
                    return 1
                # elif response.json()["status"] == 1:  # "賬戶餘額不足,請先充值"
                #     print(f"账户余额不足，账户为{user_info['account']},报错为{response.json()['msg']}")
                #     return 1
                elif response.json()["status"] == 401:
                    return 401
                    # init_login(account=user_info['account'])
                    # self.random_create_room(user_info)
                else:
                    print(f"建房失败，响应为{response.text}")
                    # init_login(account=user_info['account'])
                    return 201
                    # self.random_create_room(user_info)
            except:
                pass

    def create_battle(self, user_info):
        """
        创建对战房间，规则是：
        1、随机房间数量、随机房主、随机对战模式、随机单房间对战人数、随机箱子组合
        2、此类房间的统一标识是 title：521987
        :return: 返回创建房间的状态码、需要重新登陆的用户列表
        """
        need_login_user = []
        need_delete_user = []
        try:
            for i in range(random.randint(1, 2)):  # 循环创建的对战房间数量
                # user_info = self.yaml_control_user.read_yaml()["user_info"]
                time.sleep(1)
                user = random.choice(user_info)
                res = self.random_create_room(user)
                if res == 401:
                    need_login_user.append(user)
                elif res == 400:
                    need_delete_user.append(user)
                time.sleep(random.randint(4, 10))  # 每次创建房间间隔时间
            return 200, need_login_user, need_delete_user
        except:
            return 201, need_login_user, need_delete_user


def check_time_between(start_time, end_time):
    """
    :param start_time: 时间段开始时间
    :param end_time: 时间段结束时间
    :return: 返回各时间段的 开始时间<=当前时间<=结束时间 表达式
    """
    now = datetime.datetime.now().time()  # 获取当前时间
    start = datetime.datetime.strptime(start_time, "%H:%M").time()
    end = datetime.datetime.strptime(end_time, "%H:%M").time()
    return start <= now <= end


# ===主方法===
def auto_battle():
    battle = AutoCreateBattle()
    i = 0
    battle_wait_time = battle.config_data["battle_wait_time"]
    battle_room_limit = battle.config_data["battle_room_limit"]
    # peak_times = [("08:00", "10:00"), ("14:00", "23:00"), ("01:00", "02:00")]
    peak_times = battle.config_data["peak_times"]  # 读取高峰时间段配置
    user_list = battle.yaml_control_user.read_yaml()["user_info"]  # 获取当前有余额的用户数
    while True:
        now_time = datetime.datetime.now().strftime("%H:%M")
        if "00:20" <= now_time <= "01:30":
            break
        if len(user_list) == 0:
            now_times = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print(f"{now_times}用户的钱都花完了, 一共参与对战共{i}轮")
            break
        try:
            now_room_num = battle.get_now_room_num()  # 获取当前进行中的房间数
            # user_list = battle.yaml_control_user.read_yaml()["user_info"]  # 获取当前有余额的用户数
            if not user_list:
                print(f"用户的钱都花完了, 一共参与对战共{i}轮")
                # del user_list
                batch_add_balance(26111111110, 26111111299)
                # init_login()
            # else:
            # 判断高低谷，获取穿件房间的条件阈值
            if any(check_time_between(start_time, end_time) for start_time, end_time in peak_times):
                room_limit = battle_room_limit[0]
            else:
                room_limit = battle_room_limit[1]
            # room_limit = battle_room_limit

            if now_room_num is not None and now_room_num < room_limit:
                status, need_login_users, need_delete_users = battle.create_battle(user_list)  # 批量创建房间
                if status == 200:
                    i += 1
                    now_times = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    print(f"{now_times}  第【{i}】批对战房间创建成功，持续监听中")
                    if len(need_login_users) > 0:
                        for user in need_login_users:
                            token = init_login(account=user['account'])
                            [d.update({"token": token}) for d in user_list if d['account'] == user['account']]
                    # 没钱了就删掉
                    # if len(need_delete_users) > 0:
                    #     for user in need_delete_users:
                    #         user_list.remove(user)
                    time.sleep(battle_wait_time)
                # elif status == 400:
                #     user_list.pop()
                else:
                    time.sleep(8)
        except Exception as f:
            print(f"自动创建对战房间报错: {f}")
            # init_login()
            time.sleep(5)
            continue


if __name__ == '__main__':
    # auto_battle()
    battles = AutoCreateBattle()
    case_list = battles.get_battle_case()
    print(case_list)
    # print(YamlControl())
